package tree;
//二叉树层次遍历

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Leavel {
    // 树结点中的元素值
    public static List<List<Integer>> levelOrder(TreeNode root){
        List<List<Integer>> result = new LinkedList<>();
        Queue<TreeNode> Q = new LinkedList<>();
        if (root!=null){
            Q.offer(root);
        }
        while (Q.size()>0){
            int currsize=Q.size();
            List<Integer> val = new LinkedList<>();
            for (int i=0;i<currsize;i++){
                TreeNode node = Q.poll();
                val.add(node.val);
                if (node.left !=null){
                    Q.offer(node.left);
                }
                if (node.right!=null){
                    Q.offer(node.right);
                }
            }
            result.add(val);
        }
        return result;

    }
    public static void main(String[] args) {
        // 构造二叉树的节点
        TreeNode node6 = new TreeNode(6, null, null);
        TreeNode node7 = new TreeNode(7, null, null);
        TreeNode node9 = new TreeNode(9, null, null);
        TreeNode node8 = new TreeNode(8, node6, node7);
        TreeNode root = new TreeNode(3, node9, node8);

        // 假设printByLevels方法是你已经实现的
        List<List<Integer>> result = levelOrder(root);
        // 打印结果
        System.out.println(result);
    }

}
